import config
from random import choices
from document import Document
import contextlib
import string
from utils import *

DialogPool = {}

@contextlib.contextmanager
def getDialog(key=None):
	try:
		temp = False
		if not key:
			temp = True
			key = ''.join(choices(string.ascii_letters, config.dialog.randomLength))
			while key in DialogPool.keys():
				key = ''.join(choices(string.ascii_letters, config.dialog.randomLength))
		if key not in DialogPool.keys():
			DialogPool[key] = Dialog(key if not temp else None)
		yield DialogPool[key]
	except Exception:
		Dialog[key].reset()
	finally:
		if temp:
			Dialog.pop(key)

def clear():
	DialogPool.clear()

class Dialog(Document):
	def __init__(self, filename=None):
		Document.__init__(self, filename)
		self.__dict__['msgs'] = []
	def reset(self):
		Document.__init__(self, self.__dict__['filename'])
	def add(self, msg):
		self.__dict__['msgs'].append(msg)